<template>
  <div id="userLogin">
    <h2 class="title">用户登录</h2>
    <a-form
      style="width: 480px; margin: 0 auto"
      :model="formState"
      name="basic"
      label-align="left"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="账户名"
        name="userAccount"
        :rules="[{ required: true, message: '请输入您的账户名！' }]"
      >
        <a-input
          v-model:value="formState.userAccount"
          placeholder="请输入账户名"
        />
      </a-form-item>

      <a-form-item
        label="密码"
        name="userPassword"
        :rules="[{ required: true, message: '请输入您的密码' }]"
      >
        <a-input-password
          v-model:value="formState.userPassword"
          placeholder="请输入账户名"
        />
      </a-form-item>

      <a-form-item name="remember" :wrapper-col="{ offset: 8, span: 16 }">
        <a-checkbox v-model:checked="formState.remember">记住我</a-checkbox>
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button type="primary" html-type="submit">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from "vue";
import { userLogin } from "@/api/user";
import { useUserLoginStore } from "@/store/useUserLoginStore";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";

interface FormState {
  userAccount: string;
  userPassword: string;
  remember: boolean;
}

const formState = reactive<FormState>({
  userAccount: "",
  userPassword: "",
  remember: true,
});
const loginStore = useUserLoginStore();
const router = useRouter();
const onFinish = async (values: any) => {
  let res = await userLogin(values);
  //登录成功，把登录态保存在全局状态中
  if (res.data.code === 0 && res.data.data) {
    await loginStore.fetchLoginUser();
    message.success("登录成功！");
    router.push({
      path: "/",
      replace: true,
    });
  } else {
    message.error("账户登录失败！");
  }
  console.log("Success:", values);
};

const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};
</script>
<style scoped>
#userLogin .title {
  text-align: center;
  margin: 0 auto 15px;
}
</style>
